package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineBaseActivity;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.utils.QRCodeUtils;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.seller.offline.FragmentOffline;
import com.zhongxi.guoyuan.view.seller.offline.mode.OrderInfoOffline;
import com.zhongxi.guoyuan.view.seller.offline.mode.QrCodeBean;
import com.zhongxi.guoyuan.view.user.LoginActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/1/22.
 */

public class SellerOffLineActivity extends OffLineBaseActivity {
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.fl_container)
    FrameLayout mFlContainer;

    View lodingView; //加载中..
    View errorView;//加载失败
    View emptyView; //加载为空
    private String mName;

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_seller_offline);
        ButterKnife.bind(this);
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationIcon(R.mipmap.topback);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.seller_offline, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_cashier) {
            unsubscribe();
            mDisposable = NetWork.getOffLineApi().sellerCachierApi(RelativeUrl.OFFLINEMARKETQRCODE + MyApplication.getInstance().getUrl(),
                    MyApplication.getInstance().getCheck(true))
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showProgressDialog();
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<QrCodeBean>() {
                        @Override
                        public void accept(QrCodeBean qrCodeBean) throws Exception {
                            dismessProgressDialog();
                            MyApplication.getInstance().setSpValue(qrCodeBean.safeobj);
                            if (qrCodeBean.code == 1) {
                                if (TextUtils.isEmpty(qrCodeBean.data)) {
                                    ToastUtil.show(getString(R.string.qrinfoIncomplete));
                                } else {
                                    qrDialog(MyApplication.getInstance().parseSecutiryKey(qrCodeBean.data));
                                }
                            } else if (qrCodeBean.code == 2816) {
                                logoutDialog();
                            } else {
                                ToastUtil.show(getString(R.string.loseData, qrCodeBean.code));
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            dismessProgressDialog();
                            ToastUtil.show(getString(R.string.load_error));
                        }
                    });
        }
        return super.onOptionsItemSelected(item);
    }

    private void qrDialog(String s) {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_qroffline);
        TextView name = (TextView) view.findViewById(R.id.tv_name);
        name.setText(mName);
        ImageView cancle = (ImageView) view.findViewById(R.id.iv_cancel);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        ImageView qrcode = (ImageView) view.findViewById(R.id.iv_qrcode);
        qrcode.setImageBitmap(QRCodeUtils.createQRCode2(s, 500));
        mDialog.setView(view);
        mDialog.show();
    }

    @Override
    protected void initView() {
        super.initView();
        if (lodingView == null) {
            lodingView = UiUtils.inflate(R.layout.loadingview_layout);
        }
        if (errorView == null) {
            errorView = UiUtils.inflate(R.layout.errorview_layout);
            errorView.findViewById(R.id.page_bt).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mFlContainer.removeView(errorView);
                    loading();
                }
            });
        }
        if (emptyView == null) {
            emptyView = UiUtils.inflate(R.layout.emptyview_layout);
        }
    }

    @Override
    protected void initNetWork() {
        super.initNetWork();
        loading();
    }

    private void netWork() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().sellerOffLineInnermallApi(RelativeUrl.INNERMALL + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(true))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<OrderInfoOffline>() {
                    @Override
                    public void accept(OrderInfoOffline offline) throws Exception {
                        MyApplication.getInstance().setSpValue(offline.safeobj);
                        mFlContainer.removeView(lodingView);
                        if (offline.code == 1) {
                            if (offline.console != null && !"".equals(offline.console)) {
                                mName = offline.console.name;
                                addFragment(offline);
                            } else {
                                mFlContainer.addView(emptyView, new FrameLayout.LayoutParams(-1, -1));
                            }
                        } else if (offline.code == 9002) {
                            ToastUtil.show(getString(R.string.loseCredentials));
                            MyApplication.getInstance().sharedPrefrences.edit().putString("OffLinecredentials", "").commit();
                            finish();
                            startActivity(new Intent(UiUtils.getContext(), SellerOffLineLoginActivity.class));
                        } else if (offline.code == 9003) {
                            ToastUtil.show(getString(R.string.closedStore));
                            finish();
                        } else if (offline.code == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(getString(R.string.loseData, offline.code));
                            finish();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mFlContainer.removeView(lodingView);
                        mFlContainer.addView(errorView, new FrameLayout.LayoutParams(-1, -1));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("beneficiary", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("merchants", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("appopenid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }

    private void addFragment(OrderInfoOffline offline) {
        FragmentOffline mFragmentOffline = new FragmentOffline();
        Bundle bundle = new Bundle();
        bundle.putSerializable("offline", offline);
        mFragmentOffline.setArguments(bundle);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fl_container, mFragmentOffline)
                .commit();
    }

    Handler mHandler = new Handler();

    private void loading() {
        mFlContainer.addView(lodingView, new FrameLayout.LayoutParams(-1, -1));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            netWork();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
